package v6

import (
	"context"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/container/gmap"
	"github.com/olivere/elastic/v6"
)

var (
	EsClient      *elastic.Client
	instances   = gmap.NewStrAnyMap(true)
	DefaultName = "elaticsearch"
)

func New() *elastic.Client {
	ctx := context.Background()
	host := g.Cfg().GetString("elasticsearch.host")
	//连接客户端 注意es版本必须和包的版本一致
	client, err := elastic.NewClient(elastic.SetURL(host), elastic.SetSniff(false))
	if err != nil {
		// Handle error
		panic(err)
	}
	// Ping the Elasticsearch server to get e.g. the version number
	// ping通服务端，并获得服务端的es版本
	_, _, err = client.Ping(host).Do(ctx)
	if err != nil {
		// Handle error
		panic(err)
	}
	// 获取版本号的直接API
	_, err = client.ElasticsearchVersion(host)
	if err != nil {
		panic(err)
	}
	EsClient = client
	return client
}

// 容器封装
func Instance(name ...string) *elastic.Client {
	key := DefaultName
	if len(name) > 0 && name[0] != "" {
		key = name[0]
	}
	return instances.GetOrSetFuncLock(key, func() interface{} {
		return New()
	}).(*elastic.Client)
}

// 客户端示例
func Client(name ...string) *elastic.Client {
	return Instance(name...)
}
